package main

import (
	"github.com/codegangsta/cli"

	// "flag"
	"encoding/json"
	"fmt"
	"io/ioutil"
	"log"
	"os"
	"path/filepath"
)

type Conf struct {
	AppName string `gofm`
	Version string `v.0`
	Host    string `127.0.0.1:8085`
}

func getconf() (conf Conf) {

	var conf_file string
	app := cli.NewApp()
	app.Name = "gofm"
	app.Usage = "gofm server!"
	app.Version = "Ver.0.0"
	app.Author = "era"

	app.Flags = []cli.Flag{
		cli.StringFlag{"conf, c", "gofm.json", "Config file of path"},
	}

	app.Action = func(c *cli.Context) {
		// if len(c.Args()) > 0 {
		// = c.Args()[0]
		// }
		conf_file = c.String("conf")
	}

	app.Run(os.Args)

	if conf_file == "config.json" {
		wd, _ := filepath.Abs(os.Args[0])
		wd = filepath.Dir(wd)
		conf_file = wd + "/config.json"
	}

	if Exist(conf_file) {
		file, err := os.Open(conf_file)
		defer file.Close()
		if err != nil {
			log.Panic(err)
			os.Exit(1)
		}
		s, _ := ioutil.ReadAll(file)
		err = json.Unmarshal(s, &conf)
		if err != nil {
			log.Panic(err)
			os.Exit(1)
		}
	} else {
		fmt.Println("use flag: -c config.json")
		os.Exit(1)
	}

	return
}

func Exist(filename string) bool {
	d, err := os.Stat(filename)
	if err == nil || os.IsExist(err) {
		if d.IsDir() {
			return false
		}
		return true
	}
	return false
}
